<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="list" :props="defaultProps" default-expand-all :expand-on-click-node="false">
        <template #default="{ data }">
          <el-row type="flex" justify="space-between" style="width: 100%;">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span style="margin-right: 10px;">{{ data.managerName }}</span>
              <el-dropdown @command="fn($event,data.id)">
                <span class="el-dropdown-link">
                  下拉菜单<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <addDep ref="department" :visible.sync="visible" :current-id="currentId" @updatePage="departmentList" />
  </div>
</template>
<script>
import { delDepAPI, departmentAPI } from '@/api/department'
import { tree2List } from '@/utils/index'
import addDep from '@/views/department/components/add-dep'
export default {
  name: 'Department',
  components: {
    addDep
  },
  data() {
    return {
      list: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      visible: false,
      currentId: 0
    }
  },
  created() {
    this.departmentList()
  },
  methods: {
    async departmentList() {
      const res = await departmentAPI()

      this.list = tree2List(res.data.data)
    },
    fn(type, id) {
      if (type === 'add') {
        this.visible = true
        this.currentId = id
      }
      if (type === 'edit') {
        // 优化：进入编辑弹框 不会闪一下
        this.$refs.department.formData.id = id
        // 通过 refs 获取子组件里面方法
        this.$refs.department.depDetail(id)
        // 打开弹框
        this.visible = true
      }
      if (type === 'del') {
        this.$confirm('你确定要删除该部门吗？', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await delDepAPI(id)

          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // })
        })
      }
    }

  }
}
</script>

<style scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  margin: 10px;
}
</style>
